package vn.com.hung.notetaker.book.menus;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.Vector;

import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

import vn.com.hung.notetaker.book.components.JBNTable;
import vn.com.hung.notetaker.book.datamodels.BNTableModel;
import vn.com.hung.notetaker.utils.DialogDisplayer;

public class BNRightClickMenu extends JPopupMenu implements ActionListener{
    
    JBNTable noteTable;
    private JMenu insertRow = new JMenu("Insert Row");
    private JMenuItem rowBelowItem = new JMenuItem("Row Below", KeyEvent.VK_B);
    private JMenuItem rowAboveItem = new JMenuItem("Row Above", KeyEvent.VK_A);
    private JMenuItem saveItem = new JMenuItem("Save", KeyEvent.VK_S);
    
    public BNRightClickMenu(JBNTable noteTaker) {
        this.noteTable = noteTaker;
        
        add(insertRow);
        add(saveItem);
        
     // process insert row menu
        insertRow.add(rowAboveItem);
        insertRow.add(rowBelowItem);
        rowBelowItem.addActionListener(this);
        rowAboveItem.addActionListener(this);
        saveItem.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        JMenuItem itemClicked = (JMenuItem) ae.getSource();
        BNTableModel model = (BNTableModel) noteTable.getModel();
        if (itemClicked.equals(saveItem)) {
            System.out.println(model.getPath());
            // process save
            try {
                model.saveToCSV(model.getPath());
                DialogDisplayer.showDefaultInforDialog("Save Done!");
            } catch (IOException e) {
                DialogDisplayer.showDefaultErrorDialog("Cannot Save Data");
            }
        } else if (itemClicked.equals(rowBelowItem)) {
            // process insert row below
            Vector<Object> rowData = new Vector<Object>();
            for (int i = 0; i < model.getColumnCount(); i++) {
                rowData.add("");
            }
            model.addRow(rowData, noteTable.getSelectedCell().x + 1);
           
        } else if (itemClicked.equals(rowAboveItem)) {
            // process insert row above
            Vector<Object> rowData = new Vector<Object>();
            for (int i = 0; i < model.getColumnCount(); i++) {
                rowData.add("");
            }
            model.addRow(rowData, noteTable.getSelectedCell().x);
        }
         
    } 
    
    

}
